package com.cats.activity;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.NavUtils;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;

import com.cats.R;
import com.cats.utility.AccountManageUtility;

public class TrackActivity extends BaseActivity {
	private static String FILENAME = "TrackHistoryFile";
	private List<String> list = new ArrayList<String>();

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		System.out.println("[TrackActivity]onCreate");
		setContentView(R.layout.activity_track);
		getActionBar().setDisplayHomeAsUpEnabled(true);
		setActionBarTitle("Track");

		Button btnGoToScanActivity = (Button) findViewById(R.id.button1);
		btnGoToScanActivity.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent intent = new Intent(TrackActivity.this,
						ScanActivity.class);
				startActivityForResult(intent, HomeActivity.REQUEST_CODE_SCAN);
			}
		});

		// set list adapter
		final ListView lv = (ListView) findViewById(R.id.AboutCats);
		lv.setAdapter(new ArrayAdapter<String>(this,
				android.R.layout.simple_expandable_list_item_1, list));
		lv.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				// TODO Auto-generated method stub
				String trackIdString = (String) (lv.getItemAtPosition(arg2));
				// Do something when a list item is clicked
				System.out.println("[TrackActivity]Select:" + trackIdString);
				// navigate to shipment detail page with selected tracking
				// number
				final Intent intent = new Intent(TrackActivity.this,
						com.cats.activity.ShipmentActivity.class);
				intent.putExtra("ID", trackIdString);
				intent.putExtra("SOURCE", "com.cats.activity.TrackActivity");
				intent.putExtra("STATUS", 2); // pass a default status, delivered
				startActivity(intent);

			}
		});
	}

	// get track history data from file
	private List<String> getHistoryData() {
		String historyString = readFileAsString(FILENAME)
				.replaceAll("\\s+", "");
		System.out.println("[TrackActivity]historyString:" + historyString);
		list.clear();
		if (historyString.length() > 0 && historyString != "") {
			String[] strArray = historyString.split("[|]+");
			System.out.println("[TrackActivity]String Array:" + strArray);
			for (int i = 0; i < strArray.length; i++) {
				System.out.println("[TrackActivity]Track history item:"
						+ strArray[i]);
				list.add(strArray[i]);
			}
		}

		return list;
	}

	/**
	 * clear searching history
	 */
	@SuppressWarnings("unchecked")
	private void clearHistory() {
		writeStringAsFile("", FILENAME);
		getHistoryData();
		ListView lv = (ListView) findViewById(R.id.AboutCats);
		ArrayAdapter<String> adapter = (ArrayAdapter<String>) lv.getAdapter();
		adapter.notifyDataSetChanged();
	}

	@SuppressWarnings("unchecked")
	@Override
	/**
	 * Activity run again, reload history data
	 */
	protected void onResume() {
		super.onResume();
		System.out.println("[TrackActivity]:onResume()");
		getHistoryData();
		ListView lv = (ListView) findViewById(R.id.AboutCats);
		ArrayAdapter<String> adapter = (ArrayAdapter<String>) lv.getAdapter();
		adapter.notifyDataSetChanged();
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case android.R.id.home:
			NavUtils.navigateUpFromSameTask(this);
			return true;
		case R.id.action_clear:
			this.showConfirmWithMsg("Are you sure you want to clear the tracking history?");
			
			return true;
		}

		return super.onOptionsItemSelected(item);
	}
	
	private void showConfirmWithMsg(String msg) {
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setMessage(msg).setCancelable(false)
				.setPositiveButton("OK", new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int id) {
						clearHistory();
					}
				})
				.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						/**
						 * do nothing if cancel
						 */
					}
				});
		AlertDialog alert = builder.create();
		alert.show();
	}


	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu items for use in the action bar
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.track_activity_actions, menu);
		return super.onCreateOptionsMenu(menu);
	}

	@Override
	// get scanned number
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (resultCode == RESULT_OK) {
			Bundle b = data.getExtras();
			String barcodeString = b.getString("BARCODE");
			EditText inputEditText = (EditText) this
					.findViewById(R.id.editText1);
			inputEditText.setText(barcodeString);
			System.out.println("[TrackActivity]Scanned barcode:"
					+ barcodeString);
			// savedNumberString = barcodeString;
		}
	}

	@SuppressWarnings("unchecked")
	public void onTrackClick(View v) {
		System.out.println("[TrackActivity]:Track button clicked");
		EditText et = (EditText) findViewById(R.id.editText1);
		String inputString = et.getText().toString().replaceAll("\\s+", "");
		if (inputString.length() > 0 && inputString != null) {
			String historyString = inputString.concat("|").concat(
					readFileAsString(FILENAME));
			writeStringAsFile(historyString, FILENAME);

			getHistoryData();
			ListView lv = (ListView) findViewById(R.id.AboutCats);
			ArrayAdapter<String> adapter = (ArrayAdapter<String>) lv
					.getAdapter();
			adapter.notifyDataSetChanged();

			// navigate to shipment detail page
			final Intent intent = new Intent(TrackActivity.this,
					ShipmentActivity.class);
			intent.putExtra("ID", inputString);
			intent.putExtra("SOURCE", "com.cats.activity.TrackActivity");
			startActivity(intent);
		}
	}

	public void writeStringAsFile(final String fileContents, String fileName) {
		Context context = this.getApplicationContext();
		try {
			FileWriter out = new FileWriter(new File(context.getFilesDir(),
					fileName));
			out.write(fileContents);
			out.close();
		} catch (IOException e) {

		}
	}

	@SuppressWarnings("resource")
	public String readFileAsString(String fileName) {
		Context context = this.getApplicationContext();
		StringBuilder stringBuilder = new StringBuilder();
		String line;
		BufferedReader in = null;

		try {
			in = new BufferedReader(new FileReader(new File(
					context.getFilesDir(), fileName)));
			while ((line = in.readLine()) != null)
				stringBuilder.append(line);

		} catch (FileNotFoundException e) {

		} catch (IOException e) {

		}

		return stringBuilder.toString();
	}

	public TrackActivity() {

	}
}
